import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '../api'

export const useStudentStore = defineStore('student', () => {
  // 状态
  const students = ref([])
  const loading = ref(false)
  const currentStudent = ref(null)

  // 计算属性
  const totalStudents = computed(() => students.value.length)
  const maleStudents = computed(() => 
    students.value.filter(student => student.gender === '男').length
  )
  const femaleStudents = computed(() => 
    students.value.filter(student => student.gender === '女').length
  )

  // 按班级分组
  const studentsByClass = computed(() => {
    const grouped = {}
    students.value.forEach(student => {
      if (!grouped[student.class_name]) {
        grouped[student.class_name] = []
      }
      grouped[student.class_name].push(student)
    })
    return grouped
  })

  // 动作
  const fetchStudents = async () => {
    loading.value = true
    try {
      const response = await api.get('/students')
      students.value = response.data
    } catch (error) {
      console.error('获取学生列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchStudentById = async (id) => {
    loading.value = true
    try {
      const response = await api.get(`/students/${id}`)
      currentStudent.value = response.data
      return response.data
    } catch (error) {
      console.error('获取学生详情失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const addStudent = async (studentData) => {
    try {
      console.log('发送添加学生请求:', studentData)
      const response = await api.post('/students', studentData)
      console.log('添加学生响应:', response.data)
      students.value.push(response.data)
      return response.data
    } catch (error) {
      console.error('添加学生失败:', error)
      console.error('错误详情:', error.response?.data || error.message)
      throw error
    }
  }

  const updateStudent = async (id, studentData) => {
    try {
      const response = await api.put(`/students/${id}`, studentData)
      const index = students.value.findIndex(s => s.id === id)
      if (index !== -1) {
        students.value[index] = response.data
      }
      return response.data
    } catch (error) {
      console.error('更新学生信息失败:', error)
      throw error
    }
  }

  const deleteStudent = async (id) => {
    try {
      await api.delete(`/students/${id}`)
      students.value = students.value.filter(s => s.id !== id)
    } catch (error) {
      console.error('删除学生失败:', error)
      throw error
    }
  }

  const searchStudents = (keyword) => {
    if (!keyword) return students.value
    return students.value.filter(student => 
      student.name.includes(keyword) || 
      student.student_id.includes(keyword) ||
      student.class_name.includes(keyword)
    )
  }

  return {
    // 状态
    students,
    loading,
    currentStudent,
    // 计算属性
    totalStudents,
    maleStudents,
    femaleStudents,
    studentsByClass,
    // 动作
    fetchStudents,
    fetchStudentById,
    addStudent,
    updateStudent,
    deleteStudent,
    searchStudents
  }
}) 